﻿using System;
using UnityEngine;
using UnityEngine.Events;

namespace Simulation.Framework
{
    public class Timer
    {
        public string id;
        public float time { get; private set; }
        public TimeSpan timeSpan { get; private set; }
        public bool isCountDown = true;
        public ETimerType type = ETimerType.FIXED;
        public ETimerState state = ETimerState.IDLE;
        public UnityAction<TimeSpan> update;
        public UnityAction complete;

        private float length;

        /// <summary>
        /// 从真实时间转换到模拟时间的缩放因子
        /// </summary>
        private double timeScale;

        public Timer(float time)
        {
            id = DateTime.Now.Ticks.ToString();
            this.time = time;
            this.length = time;
            timeScale = 1;
            this.timeSpan = new TimeSpan((long)(time * TimeSpan.TicksPerSecond));
        }

        public Timer(float time, TimeSpan timeSpan)
        {
            id = DateTime.Now.Ticks.ToString();
            this.timeSpan = timeSpan;
            this.time = time;
            this.length = time;
            timeScale = time / timeSpan.TotalSeconds;
        }

        public void KeepFixedTime()
        {
           time -= Time.fixedDeltaTime;
        }

        public void KeepRealTime()
        {
            time -= Time.deltaTime;
        }

        public TimeSpan VirtualTime2TimeSpan()
        {
            double seconds = Mathf.Max(0, (float)(time / timeScale));
            TimeSpan t = isCountDown ? TimeSpan.FromSeconds(seconds) : timeSpan - TimeSpan.FromSeconds(seconds);
            return t;
        }

        public void Restart()
        {
            time = length;
        }
    }
}